import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { Top } from "../components/top/Top";
import Bottom from "../components/bottom/Bottom";
import { itemService } from "../../service/itemService";
import { cartService } from "../../service/cartService";
import "./Item.css";
import { common_utils } from "../../utils/utils";
import { v4 as uuidv4 } from 'uuid';

export default function Item() {
  const { productId } = useParams();
  const [items, setItems] = useState([]);
  const [product, setProduct] = useState({});
  const [alerts, setAlerts] = useState([]);

  useEffect(() => {
    if (productId) {
      itemService.getItems(
        productId,
        (res) => {
          const fetchedItems = res?.data.itemList;
          const receivedProduct = res?.data.product;
          if (Array.isArray(fetchedItems)) {
            setItems(fetchedItems);
            setProduct(receivedProduct);
          } else {
            console.warn("Items is not an array:", fetchedItems);
            setItems([]);
          }
        },
        (error) => {
          console.error("Error fetching items:", error);
          setItems([]);
        }
      );
    }
  }, [productId]);

  const addToCart = (item) => {
    cartService.addCartItem(common_utils.getUsername(), item.itemid, 1, (res) => {
      const alertId = uuidv4();
      setAlerts((prevAlerts) => [
        ...prevAlerts,
        { id: alertId, message: "Item added to cart!" }
      ]);
      setTimeout(() => {
        setAlerts((prevAlerts) => prevAlerts.filter((alert) => alert.id !== alertId));
      }, 2000); // Alert disappears after 2 seconds
    }, (error) => {
      console.error("Error adding item to cart:", error);
    });
  };

  return (
    <>
      <Top />
      <h2>{product.name}</h2>
      {alerts.map((alert, index) => (
        <div
          key={alert.id}
          className="alert"
          style={{
            position: 'fixed',
            top: `calc(50% + ${index * 60}px)`, // Stack alerts vertically
            left: '50%',
            transform: 'translate(-50%, -50%)',
            backgroundColor: '#4caf50',
            color: 'white',
            padding: '10px 20px',
            borderRadius: '5px',
            zIndex: 1000 + index,
            animation: 'slideIn 0.5s ease-in'
          }}
        >
          {alert.message}
        </div>
      ))}
      <ItemList items={items} addToCart={addToCart} product={product} />
      <Bottom />
      <style>
        {`
          @keyframes slideIn {
            from {
              transform: translate(-50%, -70%);
              opacity: 0;
            }
            to {
              transform: translate(-50%, -50%);
              opacity: 1;
            }
          }
        `}
      </style>
    </>
  );
}

function ItemList({ items, addToCart, product }) {
  return (
    <table>
      <thead>
        <tr>
          <th>Item ID</th>
          <th>Product ID</th>
          <th>Description</th>
          <th>List Price</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        {items?.map((item) => (
          <tr key={item.itemid}>
            <td onClick={() => {
              common_utils.jumpTo('/products/' + product.productid + '/items/' + item.itemid);
            }}>{item.itemid}</td>
            <td onClick={() => {
              common_utils.jumpTo('/products/' + product.productid + '/items/' + item.itemid);
            }}>{item.productid}</td>
            <td className="description" onClick={() => {
              common_utils.jumpTo('/products/' + product.productid + '/items/' + item.itemid);
            }}>
              <img src={common_utils.getServerImageURL(product.image)} />
              {product.description}
            </td>
            <td onClick={() => {
              common_utils.jumpTo('/products/' + product.productid + '/items/' + item.itemid);
            }}>${item.listprice.toFixed(2)}</td>
            <td>
              <button onClick={() => addToCart(item)}>Add to Cart</button>
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}